#!/bin/env python3
# -*- encoding=utf8 -*-
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: wangchong
# Create: 2021-05-19
# ******************************************************************************

"""
OBS mail notice
"""
import os
import re
import sys
import shutil
current_path = os.path.join(os.path.split(os.path.realpath(__file__))[0])
sys.path.append(os.path.join(current_path, ".."))
from concurrent.futures import ThreadPoolExecutor

import logging as log
import json
log.basicConfig(filename='a.log', level=log.INFO)
# from common.log_obs import log

class ObsMailNotice(object):
    """
    check obs proj pkg results and email notification
    """
    def __init__(self, **kwargs):
        """
        from_addr: email sender
        from_addr_pwd: email sender password
        cc_addr: cc's email
        proj: obs project name
        """
        self.kwargs = kwargs
        self.proj = self.kwargs["project"]
        self.pkglist = self.kwargs["pkglist"]
        self.to_addr_list = []
        self.dct = {}

    def _get_pkg_owner_email(self, pkg):
        """
        get the email address of the package owner
        """
        log.info("Begin to get package %s owner email..." % pkg)
        _tmpdir = os.popen("mktemp -d").read().strip('\n')
        pkg_path = os.path.join(_tmpdir, self.proj, pkg)
        cmd = "cd %s && osc co %s %s &>/dev/null && cd %s && osc up -S &>/dev/null" % (
                _tmpdir, self.proj, pkg, pkg_path)
        if os.system(cmd) == 0:
            cmd = "cd {0} && grep -A 1 \"%changelog\" *.spec | grep \"@\" && cd -".format(
                    pkg_path)
            email = os.popen(cmd).read()
            if email:
                try:
                    to_addr = re.findall(r"<(.+?)>", email)[0]
                except IndexError:
                    to_addr = "Notfound"
            else:
                to_addr = "Notfound"
            log.info("Get package %s email succeed!" % pkg)
            shutil.rmtree(_tmpdir)
        else:
            log.info("osc co %s %s failed!" % (self.proj, pkg))
            to_addr = ""
            log.info("Get package %s email failed" % pkg)
            shutil.rmtree(_tmpdir)
        # tmp = {"proj": self.proj, "pkg": pkg, "owner_email": to_addr}
        # tmp = {"proj": self.proj, "pkg": pkg, "owner_email": to_addr}
        # self.to_addr_list.append(tmp)
        self.dct[pkg] = to_addr

    def notify_all_respon_person(self):
        """
        notice all packages to person
        """
        if self.pkglist and self.proj:
            thread_arg = []
            with open(self.pkglist, 'r') as f:
                for line in f.readlines():
                    thread_arg.append(line.strip("\n"))
            with ThreadPoolExecutor(10) as executor:
                for pkg in thread_arg:
                    executor.submit(self._get_pkg_owner_email, pkg)
        else:
            log.error("Please verify proj pkglist is already exists")
        log.info(self.to_addr_list)
        with open(self.proj+".json", 'w') as f:
            json.dump(self.dct, f)

if __name__ == "__main__":
    kw = {"project":sys.argv[1], "pkglist":sys.argv[2]}
    omn = ObsMailNotice(**kw)
    omn.notify_all_respon_person()
